package io.github.jesse205.transferstation.lite.services;

import android.content.Intent;
import android.os.IBinder;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;

import java.beans.PropertyChangeListener;

import io.github.jesse205.transferstation.lite.DragDropApplication;
import io.github.jesse205.transferstation.lite.helpers.PermissionsHelper;
import io.github.jesse205.transferstation.lite.helpers.ThemeHelper;
import io.github.jesse205.transferstation.lite.sources.AppSource;

public class DragDropTileService extends TileService {
    private final PropertyChangeListener changeListener = evt -> {
        DragDropTileService.this.onAppEnabledChange((Boolean) evt.getNewValue());
    };
    private DragDropApplication application;
    private AppSource appSource;

    public DragDropTileService() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ThemeHelper.applyTheme(this);
        application = (DragDropApplication) getApplication();
        boolean appEnabled = application.isAppEnabled();
        appSource = application.getAppSource();
        if (appEnabled & application.getAppService() != null) {
            application.getAppService().checkAndStartBridgeActivity();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTileAdded() {
        super.onTileAdded();
    }

    @Override
    public void onTileRemoved() {
        super.onTileRemoved();
    }

    @Override
    public void onStartListening() {
        super.onStartListening();
        boolean appEnabled = application.isAppEnabled();
        setQsState(appEnabled);
        if (appEnabled){
            if (application.getAppService() != null) {
                application.getAppService().checkAndStartBridgeActivity();
            }
        }
        appSource.addListener(changeListener);
    }

    @Override
    public void onStopListening() {
        super.onStopListening();
        appSource.removeListener(changeListener);

    }

    @Override
    public void onClick() {
        super.onClick();
        boolean newState = !application.isAppEnabled();
        if (newState && !PermissionsHelper.askDrawOverlaysPermissionInTile(this)) {
            return;
        }
        application.setAppEnabled(newState);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    public void setQsState(boolean state) {
        getQsTile().setState(state ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE);
        getQsTile().updateTile();
    }

    public void onAppEnabledChange(boolean newState) {
        setQsState(newState);
    }
}
